package com.lktx.bbfactory.common.advice;

import com.lktx.bbfactory.common.CommonResult;
import com.lktx.bbfactory.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;

/**
 * 用于全局处理控制器里的异常
 **/
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 默认全局异常处理。
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult<String> exception(Exception e, HttpServletRequest request) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return CommonResult.failed(e.getMessage() == null ? "" : e.getMessage().replaceAll("com.lktx.equip.common.exception.BusinessException:", ""));
    }

    /**
     * 业务异常处理。
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult<String> businessException(BusinessException e) {
        log.error("business 异常信息 ex={}", e.getMessage(), e);
        return CommonResult.failed(e.getMessage() == null ? "" : e.getMessage().replaceAll("com.lktx.equip.common.exception.BusinessException:", ""));
    }

    /**
     * 方法参数校验的异常处理
     *
     * @param ex the e
     * @return ResultVO
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败，");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            //不对外暴露字段名
            sb/*.append("[").append(fieldError.getField()).append("]")*/.append(fieldError.getDefaultMessage()).append("；");
        }
        String msg = sb.substring(0, sb.length() - 1);
        return CommonResult.failed(msg);
    }






}
